var tt;
var websocket;
var lockReconnect = false;// 避免重复连接
var host = window.location.host;
var wsUrl = 'ws://' + host + '/project/webSocket/';
var baseUrl = 'ws://' + host + '/project/webSocket/';
function openSocket(){
	var userName = $("#userName").val();
	wsUrl = baseUrl+userName;
	createConnecton();
}	

function createConnecton() {
	console.log(wsUrl);
	try {
		websocket = new WebSocket(wsUrl);
		initSocket();
	} catch (e) {
		console.log('catch' + e);
		reconnect(wsUrl);
	}

}

 function reconnect(url) {
	if (lockReconnect) {
		return;
	} ;
	lockReconnect = true;
	// 没连接上会一直重连，设置延迟避免请求过多
	tt && clearTimeout(tt);
	tt = setTimeout(function() {
		createConnecton();
		lockReconnect = false;
	}, 4000);
}	
	
	
function initSocket() {
	websocket.onclose = function() {
		reconnect(wsUrl);
	};
	websocket.onerror = function() {
		reconnect(wsUrl);
	};
	websocket.onopen = function() {
		heartCheck.start();
	};
	websocket.onmessage = function(event) {
		// 拿到任何消息都说明当前连接是正常的
		$("#showMsg").append("<br/>").append(getCurrentTime()).append(": 接收信息-》").append(event.data);
		var timeout = "10000";
		var options = { 
				positionClass: "toast-bottom-left",  
				timeOut: timeout,  
				extendedTimeOut: "100000000",  
			};
		heartCheck.start();
	}
}

function sendmsg(){
	// console.log("您的浏览器支持WebSocket");
    var msgObj = {};
	msgObj.fromUser = $("#userName").val();
	msgObj.toUser = $("#toUserName").val();
	msgObj.contentText = $("#contentText").val();
    var msg = JSON.stringify(msgObj);
	$("#showMsg").append("<br/>").append(getCurrentTime()).append(": 发送信息-》 to ").append(msgObj.toUser).append(msgObj.contentText);
	websocket.send(msg);
}

/**

获取当前时间 格式：yyyy-MM-dd HH:MM:SS
*/

function getCurrentTime(){
	var nowTime=new Date();
	var month=nowTime.getMonth()+1;//一定要+1,表示月份的参数介于 0 到 11 之间。也就是说，如果希望把月设置为 8 月，则参数应该是 7。
	var date=nowTime.getDate();
	var seperator1="-";//设置成自己想要的年月日格式：年-月-日
	var seperator2=":";//设置成自己想要的时分秒格式：时:分:秒
	if(month>=1&&month<=9){
		month="0"+month;
	}
	if(date<=9){
		date="0"+date;
	}
	var currentDate=nowTime.getFullYear()+seperator1+month+seperator1+date+" "+
	nowTime.getHours()+seperator2+nowTime.getMinutes()+seperator2+nowTime.getSeconds();
	return currentDate;
}


// 心跳检测
var index=0;
var heartCheck = {
	timeout : 60000,
	timeoutObj : null,
	serverTimeoutObj : null,
	start : function() {
		console.log('start');
		var self = this;
		this.timeoutObj && clearTimeout(this.timeoutObj);
		this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
		var userName = $("#userName").val();//自己给自己发信息
		this.timeoutObj = setTimeout(function() {
			// 这里发送一个心跳，后端收到后，返回一个心跳消息，
			index++;
			var msgObj = {};
			msgObj.fromUser = userName;
			msgObj.toUser = userName;
			msgObj.contentText = "第"+index+"次检测通信";
		    var msg = JSON.stringify(msgObj);
			websocket.send(msg);
			self.serverTimeoutObj = setTimeout(function() {
				console.log('服务器连接正常..............');
				//websocket.close();
			}, self.timeout);

		}, this.timeout)
	}
}